package com.tanhua.app.interceptor;

import cn.hutool.http.HttpStatus;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
        Claims claims = JwtUtils.getClaims(token);
        Long id =Long.parseLong(claims.get("id").toString());
        String mobile = claims.get("mobile").toString();

        User user = new User();
        user.setId(id);
        user.setMobile(mobile);

        UserHolder.set(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
